<?php
/**
 * 名称：UserAction
 * 描述：后台用户管理
 * 作者：lan 时间：2013-05-02
 * 版本号：V1.0.0
 * ========================历史版本=================================
 * 序号	 版本号 	日期			姓名	 	描述
 * 1 	V1.0.0 	2013-05-02 	lan  	后台用户管理
 * ========================历史版本=================================
 * 说明：请在有更改程序的时候修改以上注释
 */
class UserAction extends CommonAction {
	public function index() {
	}
	
	/**
	 * 用户管理
	 * Create Data <2013-05-02>
	 */
	public function user() {
		import ( "ORG.Util.Page" );
		$user = model('User'); // 实例化User模型
		$ugroup = M ( 'RoleUser' );
		$lr = M ( 'Role' );
		$listRole = $lr->select ();
		$sql = "select 	DISTINCT uid,p.* from (select u.*,(select group_concat(r.name) from ".$this->_dbPrefix."role r left join ".$this->_dbPrefix."role_user ru on r.id=ru.role_id where ru.user_id=u.uid) as group_name from ".$this->_dbPrefix."user u  ";
		$field = array (
				'email',
				'sex',
				'is_active' 
		);
		
		$map = array ();
		$where =" where 1 ";
		if (isset ( $_GET ['uid'] ) && $_GET ['uid'] != '') {
			$map ['uid'] = array('in',explode(',', $_GET['uid']));
			$where .= "and uid in({$_GET['uid']}) ";
		}
		
		foreach ( $field as $v ) {
			if (isset ( $_GET [$v] ) && $_GET [$v] != '') {
				$map [$v] = array('eq',$_GET [$v]);
				$where .= "and $v='{$_GET[$v]}' ";
			}
		}
		
		if($_GET['recycle']== 1){
			$this->assign('recycle', $_GET['recycle']);
			$this->assign('recycle_tab', 'cur'); //删除用户回收站
			$map['is_del'] = 1;
			$where .= "and  is_del = 1  ";
		}else{
			$map['is_del'] = 0;
			$this->assign('user_tab', 'cur');  // 当前显示为用户不列表
			$where .= "and  is_del = 0 ";
		}
		
		
		if (isset ( $_GET ['nickname'] ) && $_GET ['nickname'] != '') {
			$map ['nickname'] = array('eq',$_GET ['nickname']);
			$where .= "and uname like '%{$_GET['nickname']}%' ";
		}
		//$display = "block";
		$this->assign ( 'rsArray', $rsArray );
		$this->assign ( $_GET );
		if (isset ( $_GET ['ugroup'] ) && $_GET ['ugroup'] != '') {
			//$sql .= "group by uid having(group_name in ($re)) ";
			$gid = $_GET ['ugroup'];
			$ssql = " select  count(* ) as c  from ".$this->_dbPrefix."user a , (SELECT uid from ( SELECT 	ru.user_id as uid FROM ".$this->_dbPrefix."role r LEFT JOIN ".$this->_dbPrefix."role_user ru ON r.id = ru.role_id  and r.id= $gid ) p) q  $where 　 and a.uid=q.uid ";
			$res = $user->query ( $ssql );
			$count = $res ['0'] ['c'];
			$p = new Page ( $count, 20 );
			$sql .= " ,( SELECT	 ru.user_id AS uid  FROM	".$this->_dbPrefix."role r	LEFT JOIN ".$this->_dbPrefix."role_user ru ON r.id = ru.role_id	AND r.id = $gid	) q ";
			$sql .= $where.'    and u.uid =q.uid';
			$sql .= " group by u.uid  order by u.uid desc limit $p->firstRow, $p->listRows ) p  left join (select r.id as rid, r.name as rname,ru.user_id from ".$this->_dbPrefix."role r left join ".$this->_dbPrefix."role_user ru on r.id=ru.role_id) yru on p.uid = yru.user_id";
			$list = $user->query ( $sql );
		}else{
			$ssql = "select count(*) as c from ".$this->_dbPrefix."user  a   $where";
			$res = $user->query ( $ssql );
			$count = $res ['0'] ['c'];
			$p = new Page ( $count, 20 );
			$sql .= $where;
			$sql .= " group by u.uid  order by u.uid desc limit $p->firstRow, $p->listRows ) p  left join (select r.id as rid, r.name as rname,ru.user_id from ".$this->_dbPrefix."role r left join ".$this->_dbPrefix."role_user ru on r.id=ru.role_id) yru on p.uid = yru.user_id";
			$list = $user->query ( $sql );
		}
		foreach ($map as $key => $val) {
			if (!is_array($val)) {
				$p->parameter .= "&$key=" . urlencode($val) . "&";
			}
		}
		
		// 用于足迹回退
		$row  = $p->firstRow?$p->firstRow:1;
		$pagenow = $row/20 +1;
		$backurl = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'].'&p='.$row;
		session('backurl',$backurl);
		
		$page = $p->show ();
		$this->assign ( 'page', $page );
		$this->assign ( 'listRole', $listRole );
		$this->assign ( 'display', $display );
		$this->assign ( 'list', $list );
		$noauthuserid = C('NOT_AUTH_ADMIN');
		$this->assign('no_auth_userid',$noauthuserid['0']);
		$this->display ();
	}
	
	public function userdialog(){
		if($_GET) {
    		if(!empty($_GET['uid'])){
    			$map['uid'] = $_GET['uid'];
    			$this->assign ( 'uid', $_GET['uid'] );
    		}
    		if(!empty($_GET['email'])){
    			$map['email'] = $_GET['email'];
    			$this->assign ( 'email', $_GET['email'] );
    		}
    		if(!empty($_GET['uname'])){
    			$map['uname'] = array ('like','%' . $_GET['uname'] . '%');
    			$this->assign ( 'uname', $_GET['uname'] );
    		}
    		$map['is_active'] = array('eq',1);
    		$user = model('User');
    		import ( "ORG.Util.Page" );
    		$count = $user->where($map)->count ();
    		$p = new Page ( $count, 10 );
    		$ulist = $user->where($map) -> field('uid,email,uname')->limit ( $p->firstRow . ',' . $p->listRows )->select();
    		$page = $p->ajax_show ();
    		$this->assign ( 'page', $page );
    		
    		$this->assign('list',$ulist);
    	}
    	$this->display();
	}
	
	/**
	 * 添加用户
	 * Create Data <2013-05-02>
	 */
	public function addUser() {
		$ugroup = M ( 'Role' ); // 实例化Role模型
		$creditType = M ( 'CreditType' );
		$user = model('User'); // 实例化User模型
		$creditUser = M ( 'CreditUser' );
		$roleUser = M ( 'RoleUser' );
		$alist = $creditType->select ();
		
		if (! empty ( $_GET ['id'] )) { // 如果id不为空，表示当前操作为根据id查询信息。
			$data ['uid'] = $_GET ['id'];
			$res = $user->where ( $data )->find ();
			
			$cu = $creditUser->where ( $data )->find ();
			
			$group = $roleUser->where ( "user_id={$_GET['id']}" )->select ();
			$this->assign ( 'groups', $group );
			$this->assign ( 'cu', $cu );
			$this->assign ( 'res', $res );
		}
		
		$list = $ugroup->select (); // 查询Role表中数据库
		if (!empty($group)) {
			$userRoles = array();
			foreach ($group as $key => $value){
				$userRoles[] = $value['role_id'];
			}
			foreach ($list as $key => $value){
				if (in_array($value['id'], $userRoles)){
					$list[$key]['is_user_role'] = 'yes';
				}
			}
		}
		$this->assign ( 'alist', $alist );
		$this->assign ( 'list', $list );
		$this->display ();
	}
	
	/**
	 * 添加用户组
	 * Create Data <2013-05-02>
	 */
	public function addUserManage() {
		$user = model('User'); // 实例化User模型
		// 参数合法性检查
		$required_field = array (
				//'email' => L ( 'email' ),
				'password' => L ( 'password' ),
				'nickname' => L ( 'nickname' ) 
		);
		foreach ( $required_field as $k => $v ) { // 判断是否为空
			if (empty ( $_POST [$k] ))
				$this->error ( $v . L ( 'notNull' ) );
		}
		if(empty($_POST['email']) && empty($_POST['phone'])){
			$this->error (  L ( 'email和手机号不能同时为空' ) );
		}
		if(!empty($_POST['email'])){
			if ($user->is_email ( $_POST ['email'] ) == '0') { // 验证email输入格式
				$this->error ( L ( 'emailFormatErrors' ) );
			}
			$res = $user->emailRepeat ( $_POST ['email'] ); // 验证email输入是否重复
			if (! empty ( $res )) {
				$this->error ( L ( 'email' ) . L ( 'exist' ) );
			}
		}
		if(!empty($_POST['phone'])){
			$res = $user->phoneRepeat ( $_POST ['phone']); // 验证email输入是否重复
			if (! empty ( $res )) {
				$this->error ( L ( '手机号码' ) . L ( 'exist' ) );
			}
		}
		
		if (strlen ( $_POST ['password'] ) < 6 || strlen ( $_POST ['password'] ) > 16) { // 验证密码输入长度
			$this->error ( L ( 'passwordMust' ) );
		}
		if ($user->is_nickname ( $_POST ['nickname'] == '0' )) { // 验证昵称输入格式
			$this->error ( L ( 'nickNameFormatErrors' ) );
		}
		
		$haveName = $user->unameRepeat ( $_POST ['nickname'] );
		
		if (is_array ( $haveName ) && sizeof ( $haveName ) > 0) {
			$this->error ( L ( 'nickname' ) . L ( 'hasBeenUsed' ) );
		}
		
		if (mb_strlen ( $_POST ['nickname'], 'UTF8' ) > 10) {
			$this->error ( L ( 'nickname' ) . L ( 'canNot' ) );
		}
		
		$data ['email'] = $_POST ['email'];
		$data ['phone'] = $_POST ['phone'];
		$data ['uname'] = $_POST ['nickname'];
		$data ['password'] = md5 ( $_POST ['password'] );
		$data ['domain'] = $_POST ['domain'];
		$data ['ctime'] = time ();
		$data ['is_active'] = intval ( $_POST ['isActive'] );
		$data ['sex'] = intval ( $_POST ['sex'] );
		$data ['is_init'] = '1';
		$data ['register_ip'] = get_client_ip ();
		$data ['login_ip'] = get_client_ip ();
		$data['admin_level'] = empty($_POST ['group'])?'0':'1';
		
		$_LOG ['uid'] = $this->mid;
		$_LOG ['type'] = '1';
		$datas [] = L ( 'user' ) . ' - ' . L ( 'userManage' );
		if ($_POST ['__hash__'])
			unset ( $_POST ['__hash__'] );
		$datas [] = $_POST;
		$_LOG ['data'] = serialize ( $datas );
		$_LOG ['ctime'] = time ();
		M ( 'AdminLog' )->add ( $_LOG );
		
		/*
		if (! empty ( $_POST ['domain'] )) {
			$us = $user->domainRepeat ( $_POST ['domain'] );
			if ($us) {
				$this->error ( L ( 'domain' ) . L ( 'hasBeenUsed' ) );
			}
		}		
		// 域名只能以英文字母开头
		if (! ereg ( '^[a-zA-Z][a-zA-Z0-9]+$', $_POST ['domain'] )) {
			$this->error ( L ( 'domain' ) . L ( 'canOnly' ) );
		}
		
		// 域名需大于1个字符
		if (strlen ( $_POST ['domain'] ) < 2) {
			$this->error ( L ( 'domain' ) . L ( 'mustBe' ) );
		}
		
		// 域名需小于20个字符
		if (strlen ( $_POST ['domain'] ) > 20) {
			$this->error ( L ( 'domain' ) . L ( 'lessThan' ) );
		}
		*/
		
		$uid = $user->add ( $data ); // 添加完成后返回用户id
		if (! $uid) {
			$this->error ( L ( 'sorry' ) ); // 用户id不存在，则退出执行，提示失败
			exit ();
		} else {
			$credit = M ( 'CreditType' );
			$credit_type = $credit->order ( 'id asc' )->select ();
			foreach ( $credit_type as $v ) { // 添加用户积分
				$credit_action [$v ['name']] = intval ( $_POST [$v ['name']] );
			}
			if ($credit_action) {
				$creditUserDao = M ( 'CreditUser' );
				foreach ( $credit_type as $vs ) {
					$data [$vs ['name']] = intval ( $_POST [$vs ['name']] );
				}
				$data ['uid'] = $uid;
				if (! $creditUserDao->add ( $data )) {
					$this->error ( L ( 'sorry' ) );
					exit ();
				}
			}
		}
		// 添加用户组信息
		if (! empty ( $_POST ['group'] )) {
			model ( 'UserGroup' )->addUserGroup ( $uid, $_POST ['group'] );
		}
		$this->success ( L ( 'registration' ) . L ( 'success' ), URL( 'admin/User/user' ) );
	}
	
	/**
	 * 修改用户
	 * Create Data <2013-05-02>
	 */
	public function editUser() {
		$user = model('User'); // 实例化User模型
		                      // 参数合法性检查
		$required_field = array (
				//'email' => L ( 'email' ),
				// 'password' => L ( 'password' ),
				'nickname' => L ( 'nickname' ) 
		);
		foreach ( $required_field as $k => $v ) { // 判断是否为空
			if (empty ( $_POST [$k] ))
				$this->error ( $v . L ( 'notNull' ) );
		}
		if(empty($_POST['email']) && empty($_POST['phone'])){
			$this->error (  L ( 'email和手机号不能同时为空' ) );
		}
		if(!empty($_POST['email'])){
			if ($user->is_email ( $_POST ['email'] ) == '0') { // 验证email输入格式
				$this->error ( L ( 'emailFormatErrors' ) );
			}
			$res = $user->emailRepeat ( $_POST ['email'], $_POST ['uid'] ); // 验证email输入是否重复
			if (! empty ( $res )) {
				$this->error ( L ( 'email' ) . L ( 'exist' ) );
			}
		}
		if(!empty($_POST['phone'])){
			$res = $user->phoneRepeat ( $_POST ['phone'], $_POST ['uid'] ); // 验证email输入是否重复
			if (! empty ( $res )) {
				$this->error ( L ( '手机号码已' ) . L ( 'exist' ) );
			}
		}
		
		if ($user->is_nickname ( $_POST ['nickname'] == '0' )) { // 验证昵称输入格式
			$this->error ( L ( 'nickNameFormatErrors' ) );
		}
		
		$haveName = $user->unameRepeat ( $_POST ['nickname'], $_POST ['uid'] );
		if (is_array ( $haveName ) && sizeof ( $haveName ) > 0) {
			$this->error ( L ( 'nickname' ) . L ( 'hasBeenUsed' ) );
		}
		
		if (mb_strlen ( $_POST ['nickname'], 'UTF8' ) > 10) {
			$this->error ( L ( 'nickname' ) . L ( 'canNot' ) );
		}
		
		$data ['uid'] = $_POST ['uid'];
		$data ['email'] = $_POST ['email'] ===''?null:$_POST ['email'];
		$data ['phone'] = $_POST ['phone'];
		$data ['uname'] = $_POST ['nickname'];
		$pass = $user->where ( "uid={$_POST['uid']}" )->getField ( 'password' );
		if (empty ( $_POST ['password'] )) {
			$data ['password'] = $pass;
		} else {
			$data ['password'] = md5 ( $_POST ['password'] );
		}
		$data ['domain'] = $_POST ['domain'];
		$data ['ctime'] = time ();
		$data ['is_active'] = intval ( $_POST ['isActive'] );
		$data ['admin_level'] = intval ( $_POST ['admin_level'] );
		$data ['sex'] = intval ( $_POST ['sex'] );
		$data ['is_init'] = '1';
		$data ['salt'] = '';
		$data ['register_ip'] = get_client_ip ();
		$data ['login_ip'] = get_client_ip ();
		//$data['admin_level'] = empty($_POST ['group'])?'0':'1';
		
		$is_super_administrator = false;
		$origin_admin_level = $user->where ( "uid={$_POST['uid']}" )->getField ( 'admin_level' );
		$origin_role_id = M("role_user") ->where ( "user_id={$_POST['uid']}" )->getField ( 'role_id' );
		if(empty($origin_role_id) && $origin_admin_level==="1"){
			$is_super_administrator = true;
			//$data['admin_level'] = 1;
		}
		$_LOG ['uid'] = $this->mid;
		$_LOG ['type'] = '3';
		$datas [] = L ( 'user' ) . ' - ' . L ( 'userManage' );
		if ($_POST ['__hash__'])
			unset ( $_POST ['__hash__'] );
		$datas [] = $_POST;
		$_LOG ['data'] = serialize ( $datas );
		$_LOG ['ctime'] = time ();
		M ( 'AdminLog' )->add ( $_LOG );
		
		if (! empty ( $_POST ['domain'] )) {
			// 域名只能以英文字母开头
			if (! ereg ( '^[a-zA-Z][a-zA-Z0-9]+$', $_POST ['domain'] )) {
				$this->error ( L ( 'domain' ) . L ( 'canOnly' ) );
			}
			// 域名需大于1个字符
			if (strlen ( $_POST ['domain'] ) < 2) {
				$this->error ( L ( 'domain' ) . L ( 'mustBe' ) );
			}
			// 域名需小于20个字符
			if (strlen ( $_POST ['domain'] ) > 20) {
				$this->error ( L ( 'domain' ) . L ( 'lessThan' ) );
			}
			$us = $user->domainRepeat ( $_POST ['domain'], $_POST ['uid'] );
			if ($us) {
				$this->error ( L ( 'domain' ) . L ( 'hasBeenUsed' ) );
			}
		}
		
		
		$uid = $user->save ( $data ); // 添加完成后返回用户id
		if (false !== $uid) {
			$credit = M ( 'CreditType' );
			$credit_type = $credit->order ( 'id asc' )->select ();
			foreach ( $credit_type as $v ) { // 添加用户积分
				$credit_action [$v ['name']] = intval ( $_POST [$v ['name']] );
			}
			if ($credit_action) {
				$creditUserDao = M ( 'CreditUser' );
				foreach ( $credit_type as $vs ) {
					$datac [$vs ['name']] = intval ( $_POST [$vs ['name']] );
				}
				if (false === $creditUserDao->where ( "uid={$_POST['uid']}" )->save ( $datac )) {
					$this->error ( L ( 'sorry' ) );
					exit ();
				}
			}
		} else {
			$this->error ( L ( 'sorry' ) ); // 用户id不存在，则退出执行，提示失败
			exit ();
		}
		if(!$is_super_administrator){
			// 修改用户组信息
			model ( 'UserGroup' )->addUserGroup ( $_POST ['uid'], implode(',',$_POST ['group']) );
		}

		$this->success ( L ( 'editor' ) . L ( 'success' ), URL ( 'admin/User/user' ) );
	}
	
	/**
	 * 删除用户
	 * Create Data <2013-05-02>
	 */
	public function doDeleteUser() {
		$_POST ['ids'] = explode ( ',', $_POST ['ids'] );
		if ( empty($_POST['ids']) ) return false;
		$no_auth_userid = C('NOT_AUTH_ADMIN');
		foreach ($_POST['ids'] as $k => $v){
			if ($v == $no_auth_userid['0']) {
				unset($_POST['ids'][$k]);
			}
		}

		$mm['uid'] = array('in', $_POST ['ids']);
		$list = M('User')->where($mm)->field('email')->select();
		$d = array();
		foreach ($list as $k=>$v) {
			$d['email'] .= $v['email'].',';
		}
		$member_uid = $_POST ['ids'];
		$_LOG ['uid'] = $this->mid;
		$_LOG ['type'] = '2';
		$data [] = L ( 'user' ) . ' - ' . L ( 'userManage' );
		$map ['uid'] = array (
				'in',
				$_POST ['ids'] 
		);
		$data [] = model('User')->where ( $map )->select ();
		$_LOG ['data'] = serialize ( $data );
		$_LOG ['ctime'] = time ();
		M ( 'AdminLog' )->add ( $_LOG );
		$res = model('User')->deleteUser ( $_POST ['ids'] );
		if ($res) {
			$x = common('Url')->getSysOperUrl('syndeleteuser',$d);
			echo $x;
		} else {
			echo 0;
			return;
		}
	}
	
	/**
	 * 逻辑删除用户
	 * 
	 */
	public function doDelUser(){
		$_POST ['ids'] = explode ( ',', $_POST ['ids'] );
		if ( empty($_POST['ids']) ) return false;
		$no_auth_userid = C('NOT_AUTH_ADMIN');
		foreach ($_POST['ids'] as $k => $v){
			if ($v == $no_auth_userid['0']) {
				unset($_POST['ids'][$k]);
			}
		}
		$ids ="";
		foreach ($_POST['ids']  as $v){
			$ids .= $v." ,";
		}
		$ids = substr($ids,0,strlen($ids)-1);
		$res = M("User") -> where("`uid` in (".$ids.")") -> setField("is_del",1);
		if ($res) {
			echo 1;
		} else {
			echo 0;
			return;
		}
	}
	
	/**
	 * 恢复逻辑删除用户
	 */
	public function doRecUser(){
		$res = M("User") -> where("`uid` in (".$_POST[ids].")") -> setField("is_del",0);
		if ($res) {
			echo 1;
		} else {
			echo 0;
			return;
		}
	}
	
	/**
	 * 用户管理组
	 * Create Data <2013-05-02>
	 */
	public function userGroupManage() {
		$ugroup = M ( 'Role' ); // 实例化Role模型
		$list = $ugroup->select (); // 查询Role表中数据库
		$this->assign ( 'list', $list );
		$this->display ();
	}
	
	/**
	 * 添加用户管理组
	 * Create Data <2013-05-02>
	 */
	public function addUserGroupManage() {
		$role = M ( 'Role' );
		if (! empty ( $_GET ['id'] )) { // 如果id不为空，表示当前操作为根据id查询信息。
			$data ['id'] = $_GET ['id'];
			$res = $role->where ( $data )->find ();
			$this->assign ( 'res', $res );
		}
		$this->display ();
	}
	
	/**
	 * 添加用户管理组
	 * Create Data <2013-05-02>
	 */
	public function addGroupManage() {
		$role = M ( 'Role' );
		$res = $this->isUserGroupExist ( $_POST ['name'] ); // 判断添加的用户管理组名是否存在
		if (! empty ( $res )) {
			$this->error ( L ( 'userGroupManage' ) . L ( 'name' ) . L ( 'exist' ) );
		} else {
			
			$data ['name'] = $_POST ['name'];
			$data ['create_time'] = time ();
			$data ['status'] = $_POST ['status'];
			
			$log ['uid'] = $this->mid;
			$log ['type'] = 1;
			$datas [] = L ( 'user' ) . ' - ' . L ( 'userGroupManage' );
			if ($_POST ['__hash__'])
				unset ( $_POST ['__hash__'] );
			$datas [] = $_POST;
			$log ['data'] = serialize ( $datas );
			$log ['ctime'] = time ();
			M ( 'AdminLog' )->add ( $log );
			
			if (false !== $role->add ( $data )) {
				$this->assign ( 'jumpUrl', URL ( 'admin/User/userGroupManage' ) );
				$this->success ( L ( 'save' ) . L ( 'success' ) );
			} else {
				$this->error ( L ( 'save' ) . L ( 'fails' ) );
			}
		}
	}
	
	/**
	 * 修改用户管理组
	 * Create Data <2013-05-02>
	 */
	public function editGroupManage() {
		$role = M ( 'Role' );
		$id = $_POST ['id']; // 接受页面传过来的参数
		$res = $this->isUserGroupExist ( $_POST ['name'], $id ); // //判断修改的用户组名是否存在
		if (! empty ( $res )) {
			$this->error ( L ( 'userGroupManage' ) . L ( 'name' ) . L ( 'exist' ) );
		} else {
			$data ['name'] = $_POST ['name'];
			$data ['update_time'] = time ();
			$data ['status'] = $_POST ['status'];
			
			$log ['uid'] = $this->mid;
			$log ['type'] = 3;
			$datas [] = L ( 'user' ) . ' - ' . L ( 'userGroupManage' );
			if ($_POST ['__hash__'])
				unset ( $_POST ['__hash__'] );
			$datas [] = $_POST;
			$log ['data'] = serialize ( $datas );
			$log ['ctime'] = time ();
			
			M ( 'AdminLog' )->add ( $log );
			
			if (false !== $role->where ( "id=$id" )->save ( $data )) {
				$this->assign ( 'jumpUrl', URL ( 'admin/User/userGroupManage' ) );
				$this->success ( L ( 'editor' ) . L ( 'success' ) );
			} else {
				$this->error ( L ( 'editor' ) . L ( 'fails' ) );
			}
		}
	}
	
	/**
	 * 用户管理组名称是否存在
	 * Create Data <2013-05-02>
	 */
	public function isUserGroupExist($name, $gid = 0) {
		$map ['id'] = array (
				'neq',
				$gid 
		);
		$map ['name'] = $name;
		return M ( 'Role' )->where ( $map )->find ();
	}
	
	/**
	 * 删除用户管理组 删除用户管理的同时删除yl_access、yl_role、yl_role_user表中的数据
	 * Create Data <2013-05-02>
	 */
	public function delUserGroupManage() {
		$role = M ( 'Role' );
		$access = M ( 'Access' );
		$roleUser = M ( 'RoleUser' );
		
		$id = $_POST ['ids'];
		if (empty ( $id )) {
			echo 0;
			exit ();
		}
		$map ['id'] = array (
				'in',
				$id 
		);
		$data ['role_id'] = array (
				'in',
				$id 
		);
		
		$log ['uid'] = $this->mid;
		$log ['type'] = 2;
		$datas [] = L ( 'user' ) . ' - ' . L ( 'userGroupManage' );
		if ($_POST ['__hash__'])
			unset ( $_POST ['__hash__'] );
		$datas [] = $_POST;
		$log ['data'] = serialize ( $datas );
		$log ['ctime'] = time ();
		M ( 'AdminLog' )->add ( $log );
		
		if ($roleUser->where ( $data )->find ()) {
			echo '2';
		} else {
			
			if (false !== $role->where ( $map )->delete ()) {
				echo false !== $access->where ( $data )->delete () ? '1' : '0';
			}
		}
	}
	
	/**
	 * 用户组
	 * Create Data <2013-05-02>
	 */
	public function userGroup() {
		$ug = model ( 'UserGroup' );
		$list = $ug->order ( 'min_credit' )->select ();
		$this->assign ( 'list', $list );
		$this->display ();
	}
	
	/**
	 * 添加用户组
	 * Create Data <2013-05-02>
	 */
	public function addUserGroup() {
		$ug = model ( 'UserGroup' );
		import ( "ORG.Io.Dir" );
		$dirs = new Dir ('./public/icon' );
		foreach ( $dirs as $key => $value ) {
			if (in_array ( $value ['ext'], array (
					'gif',
					'jpg',
					'png' 
			) )) {
				$dir [] = $value;
			}
		}
		$this->assign ( 'iconlist', $dir );
		
		if (! empty ( $_GET ['id'] )) { // 如果id不为空，表示当前操作为根据id查询信息。
			$data ['user_group_id'] = $_GET ['id'];
			$res = $ug->where ( $data )->find ();
			$this->assign ( 'res', $res );
		}
		$this->display ();
	}
	/**
	 * 添加用户组操作
	 * Create Data <2013-05-02>
	 */
	public function addGroup() {
		$ug = model ( 'UserGroup' );
		$count = $ug->count ();
		$maxCredit = $_POST ['max_credit'];
		$star = $_POST ['star'];
		
		$data ['title'] = $_POST ['title'];
		$data ['star'] = $star;
		$data ['ctime'] = time ();
		$data ['icon'] = $_POST ['icon'];
		
		$r = $ug->titleRepeat($_POST['title']);
		if(!empty($r)) {
			$this->error(L('name').L('having'));
		}
		
		if ($count == 0) {
			$data ['min_credit'] = '0';
			$data ['max_credit'] = $maxCredit;
		} else {
			$m = $ug->maxCrediteRepeat($maxCredit);
			if(!empty($m)) {
				$this->error(L('score').L('having'));
			}
			
			$map ['max_credit'] = array (
					'gt',
					$maxCredit 
			);
			
			$find = $ug->where ( $map )->order('max_credit')->find ();
			if ($find) {
				$max ['max_credit'] = $maxCredit;
				$ug->where ( "user_group_id={$find['user_group_id']}" )->save ( $max );
				
				$data ['min_credit'] = $maxCredit;
				$data ['max_credit'] = $find ['max_credit'];
			} else {
				$finds = $ug->max ( 'max_credit' );
				if ($finds) {
					$data ['min_credit'] = $finds;
					$data ['max_credit'] = $maxCredit;
				}
			}
		}
		/* 操作日志 */
		$log ['uid'] = $this->mid;
		$log ['type'] = 1;
		$datas [] = L ( 'user' ) . ' - ' . L ( 'userGroup' );
		if ($_POST ['__hash__'])
			unset ( $_POST ['__hash__'] );
		$datas [] = $_POST;
		$log ['data'] = serialize ( $datas );
		$log ['ctime'] = time ();
		M ( 'AdminLog' )->add ( $log );
		
		
		if ($ug->add ( $data )) {
			$this->success ( 'success', URL ( 'admin/User/userGroup' ) );
		} else {
			$this->error ( 'error' );
		}
	}
	
	/**
	 * 编辑用户组
	 * Create Data <2013-05-02>
	 */
	public function editGroup() {
		$ug = model('UserGroup');
		$data['user_group_id'] = $_POST['id'];
		$data ['title'] = $_POST ['title'];
		$maxCredit = intval($_POST["max_credit"]);
		$data ['star'] = $star;
		$data ['ctime'] = time ();
		$data ['icon'] = $_POST ['icon'];
		/* 当前输入的最大值不能小于0 */
		if(intval($maxCredit) < 0) {
			$this->error(L('canNotThan'));  
		}
		
		/* 判断名称是否重复 */
		$r = $ug->titleRepeat($_POST['title'],$_POST['id']); 
		if(!empty($r)) {
			$this->error(L('name').L('having'));
		}
		/* 判断积分是否重复 */
		$m = $ug->maxCrediteRepeat($maxCredit,$_POST['id']);
		if(!empty($m)) {
			$this->error(L('score').L('having'));
		}
		
		/* 查找当前修改积分的最小值的最大值是否存在 */
		$mx = $ug->where("min_credit={$_POST['hiddmaxcredit']}")->find();
		if(!empty($mx)) { 
			if($maxCredit > $mx['max_credit']) {
				$this->error(L('inputCanNot').$mx['max_credit']);
			}
			$data['max_credit'] = $maxCredit;
			if(false !== $ug->save($data)) {
				$ms['min_credit'] = $maxCredit;
				$ug->where("user_group_id={$mx['user_group_id']}")->save($ms);
				$this->success(L('editor').L('success'),URL('admin/user/userGroup'));
			}
		} else {
			//$this->error(L('integralMax'));
			echo $ug->getlastsql();
		}
	}
	
	/**
	 * 删除用户组
	 * Create Data <2013-05-02>
	 */
	public function deleteUserGroup() {
		echo 1;
	}
	 
	/**
	 * 资料配置
	 * Create Data <2013-05-02>
	 */
	public function dataConfig() {
		$us = M ( 'UserSet' );
		$list = $us->order ( 'id' )->select ();
		$this->assign ( 'list', $list );
		$this->display ();
	}
	
	/**
	 * 修改用户配置的状态
	 * Create Data <2013-05-02>
	 */
	public function setStatus() {
		$us = M ( 'UserSet' );
		$data ['id'] = $_GET ['id'];
		$re = $us->where ( $data )->find ();
		
		if ($re ['status'] == '1') {
			$statusId = '0';
		} else {
			$statusId = '1';
		}
		
		$data ['status'] = $statusId;
		if (false !== $us->save ( $data )) {
			$this->success ( L ( 'settings' ) . L ( 'success' ),URL( 'admin/User/dataConfig' ) );
		} else {
			$this->error ( L ( 'settings' ) . L ( 'fails' ) );
		}
	}
	
	/**
	 * 修改用户空间显示状态
	 * Create Data <2013-05-02>
	 */
	public function setSpace() {
		$us = M ( 'UserSet' );
		$data ['id'] = $_GET ['id'];
		$re = $us->where ( $data )->find ();
		
		if ($re ['showspace'] == '1') {
			$statusId = '0';
		} else {
			$statusId = '1';
		}
		
		$data ['showspace'] = $statusId;
		if (false !== $us->save ( $data )) {
			$this->success ( L ( 'settings' ) . L ( 'success' ),URL( 'admin/User/dataConfig' ));
		} else {
			$this->error ( L ( 'settings' ) . L ( 'fails' ) );
		}
	}
	
	/**
	 * 添加字段
	 * Create Data <2013-05-02>
	 */
	public function addField() {
		if ($_POST) {
			$us = M ( 'UserSet' );
			$fieldkey = trim ( $_POST ['fieldkey'] );
			$fieldname = trim ( $_POST ['fieldname'] );
			
			if (empty ( $fieldkey ) || empty ( $fieldname )) {
				$this->assign ( 'waitSecond', 1 );
				$this->error ( L ( 'field' ) . L ( 'keyName' ) . L ( 'and' ) . L ( 'field' ) . L ( 'name' ) . L ( 'notNull' ) );
			}
			
			$_LOG ['uid'] = $this->mid;
			$_LOG ['type'] = '1';
			$datas [] = L ( 'user' ) . ' - ' . L ( 'dataConfig' );
			if ($_POST ['__hash__'])
				unset ( $_POST ['__hash__'] );
			$datas [] = $_POST;
			$_LOG ['data'] = serialize ( $datas );
			$_LOG ['ctime'] = time ();
			M ( 'AdminLog' )->add ( $_LOG );
			
			$data ['fieldkey'] = $fieldkey;
			if ($us->where ( $data )->count () == 0) {
				$data ['fieldname'] = $fieldname;
				$data ['status'] = intval ( $_POST ['status'] );
				$data ['module'] = $_POST ['module'];
				$data ['showspace'] = intval ( $_POST ['showspace'] );
				
				if ($us->add ( $data )) {
					$this->success ( L ( 'add' ) . L ( 'success' ), URL ( 'admin/User/dataConfig' ) );
				} else {
					$this->error ( L ( 'add' ) . L ( 'fails' ) );
				}
			} else {
				$this->assign ( 'waitSecond', 1 );
				$this->error ( L ( 'field' ) . L ( 'keyName' ) . L ( 'exist' ) );
			}
		} else {
			$this->display ();
		}
	}
	
	/**
	 * 删除字段
	 * Create Data <2013-05-02>
	 */
	public function delField() {
		$us = M ( 'UserSet' );
		
		$ids = $_POST ['ids'];
		if (empty ( $ids )) {
			echo 0;
			exit ();
		}
		
		/* 添加日志 */
		$log ['uid'] = $this->mid;
		$log ['type'] = '2';
		$datas [] = L ( 'user' ) . ' - ' . L ( 'dataConfig' );
		if ($_POST ['__hash__'])
			unset ( $_POST ['__hash__'] );
		$datas [] = $_POST;
		$log ['data'] = serialize ( $datas );
		$log ['ctime'] = time ();
		M ( 'AdminLog' )->add ( $log );
		
		$data ['id'] = array (
				'in',
				$ids 
		);
		echo $us->where ( $data )->delete () ? '1' : '0';
	}
    
	/**
	 * 消息群发 
	 * Create Data <2013-05-02>
	 */
    public function massNews() {
		$role = M ( 'Role' );
		
		$list = $role->order ( 'id' )->select ();
		
		$this->assign ( 'list', $list );
		$this->display ();
	}
	
	/**
	 * 消息群发设置
	 * Create Data <2013-05-02>
	 */
	public function massNewsSettings() {
		set_time_limit ( 0 );
		$id = intval ( $_POST ['id'] );
		$type = intval ( $_POST ['type'] );
		$ru = M ( 'RoleUser' );
		$user = M ( 'User' );
		
		// 如果id=0，表示所有用户,获取所有用户的uid
		if ($id == 0) {
			$data ['is_active'] = array (
					'eq',
					'1' 
			);
			$list = $user->where ( $data )->field ( 'uid' )->order ( 'uid' )->select ();
			$count = $user->where($data)->field('uid')->order('uid')->count();
		} else {
			$count = $ru->where ( "role_id=$id" )->count ();
			$list = $ru->where ( "role_id=$id" )->select ();
		}
		$title = trim ( $_POST ['title'] );
		$content = trim ( $_POST ['content'] );
		if (empty ( $title )) {
			$this->error ( L ( 'pleaseFillIn' ) . L ( 'title' ) );
		}
		if (empty ( $content )) {
			$this->error ( L ( 'pleaseFillIn' ) . L ( 'content' ) );
		}
		$res = false;
		if ($count > 0) {
			// 如果type==1标识发送的系统消息
			if ($type == 1) {
				$map ['type'] = 'admin_notification';
				$map ['data'] = serialize ( array (
						'title' => $title,
						'body' => $content 
				) );
				$map ['ctime'] = time ();
				$map ['from'] = $this->mid;
				foreach ( $list as $alist ) {
					if ($id == 0) {
						$map ['receive'] = $alist ['uid'];
					} else {
						$map ['receive'] = $alist ['user_id'];
					}
					$res = M ( 'Notify' )->add ( $map );
				}
			} else {
				foreach ( $list as $alist ) {
					if ($id == 0) {
						$ids [] = $alist ['uid'];
					} else {
						$ids [] = $alist ['user_id'];
					}
				}
				$map ['uid'] = array (
						'in',
						$ids 
				);
				$ps = $user->where ( $map )->field ( 'email' )->select ();
				$arr = array ();
				foreach ( $ps as $key => $p ) {
					$arr [] = $p ['email'];
				}
				$res = common('Email')->SendMail($arr,$content,$title);
			}
			if ($res) {
				// 添加日志
				$log ['uid'] = $this->mid;
				$log ['type'] = 1;
				$datas [] = L ( 'user' ) . ' - ' . L ( 'massNews' );
				if ($_POST ['__hash__'])
					unset ( $_POST ['__hash__'] );
				$datas [] = $_POST;
				$log ['data'] = serialize ( $datas );
				$log ['ctime'] = time ();
				M ( 'AdminLog' )->add ( $log );
				
				$this->success ( L ( 'send' ) . L ( 'success' ) );
			} else {
				$this->error ( L ( 'send' ) . L ( 'fails' ) );
			}
		} else {
			$this->error ( L ( 'pleaseUsers' ) );
		}
	}
	
	/**
	 * 邀请统计
	 * Create Data <2013-05-02>
	 */
	public function inviteStatis() {
		import("ORG.Util.Page"); 
		
		$ir = model('InviteRecord');
		$uid = $_POST ['uid'];
		if (! empty ( $uid )) {
			$data ['ed.uid'] = array (
					'in',
					$uid 
			);
		}
		
		$list = $ir->table ( C ( 'DB_PREFIX' ) . 'invite_record as ed' )->join ( C ( 'DB_PREFIX' ) . 'user as u on ed.uid=u.uid' )->field ( 'ed.uid,count(ed.uid) as c,u.uname' )->where ( $data )->group ( 'ed.uid' )->select ();
		$this->assign ( 'id', $uid );
		$this->assign ( 'list', $list );
		$ir->count('distinct uid');
		$this->display ();
	}
	
	/**
	 * 查看全部
	 * Create Data <2013-05-02>
	 */
	public function viewAll() {
		$ir = model('InviteRecord');
		$id = $_GET ['id'];
		$list = $ir->table ( C ( 'DB_PREFIX' ) . 'invite_record as ed' )->join ( C ( 'DB_PREFIX' ) . 'user as u on ed.fid=u.uid' )->field ( 'ed.*,u.uname' )->where ( "ed.uid=$id" )->select ();
		
		$this->assign ( 'list', $list );
		$this->display ();
	}
	
	/**
	 * 登录日志
	 * Create Data <2013-05-02>
	 */
	public function loginLog() {
		$lr = M ( 'LoginRecord' );
		import ( "ORG.Util.Page" );
		$count = $lr->count ();
		$p = new Page ( $count, 20 );
		$list = $lr->table ( C ( 'DB_PREFIX' ) . 'login_record as lg' )->join ( C ( 'DB_PREFIX' ) . 'user as u on lg.uid=u.uid' )->field ( 'lg.*,u.uname' )->order ( 'uid' )->limit ( $p->firstRow . ',' . $p->listRows )->select ();
		$page = $p->show ();
		$this->assign ( 'page', $page );
		$this->assign ( "list", $list );
		$this->display ();
	}
	
	/**
	 * 删除登录日志
	 * Create Data <2013-05-02>
	 */
	public function delUserLoginLogManage() {
		$ugroup = M ( 'LoginRecord' );
		if (empty ( $_POST ['ids'] )) {
			echo 0;
			exit ();
		}
		
		$log ['uid'] = $this->mid;
		$log ['type'] = 2;
		$datas [] = L ( 'user' ) . ' - ' . L ( 'loginLog' );
		if ($_POST ['__hash__'])
			unset ( $_POST ['__hash__'] );
		$datas [] = $_POST;
		$log ['data'] = serialize ( $datas );
		$log ['ctime'] = time ();
		M ( 'AdminLog' )->add ( $log );
		
		$map ['uid'] = array (
				'in',
				$_POST ['ids'] 
		);
		echo $ugroup->where ( $map )->delete () ? '1' : '0';
	}
	
	/**
	 * 添加节点
	 * Create Data <2013-05-02>
	 */
	public function addNodeManage() {
		$pid = $_POST ['pid'];
		$node = model ( 'Node' );
		
		if (isset ( $pid )) {
			
			$data ['name'] = $_POST ['name'];
			$data ['pid'] = $pid;
			$data ['title'] = $_POST['name'];
			
			$log ['uid'] = $this->mid;
			$log ['type'] = 1;
			$datas [] = L ( 'user' ) . ' - ' . L ( 'nodeManage' );
			if ($_POST ['__hash__'])
				unset ( $_POST ['__hash__'] );
			$datas [] = $_POST;
			$log ['data'] = serialize ( $datas );
			$log ['ctime'] = time ();
			M ( 'AdminLog' )->add ( $log );
			
			if ($node->getById ( $pid )) {
				$level = $node->level;
				$data ['level'] = array (
						'exp',
						"$level+1" 
				);
			} else {
				$data ['level'] = 1;
			}
			//echo $node->add ( $data ) ? '2' : '0';
			$result = $node->add($data);
			if($result) {
				$id = $node->where("id=$result")->find();
				echo json_encode ( $id );
			} else {
				echo 0;
			}
		}
	}
	
	/**
	 * 删除节点
	 * Create Data <2013-05-02>
	 */
	public function delNode() {
		$node = model ( 'Node' );
		$assess = M ( 'Access' );
		$ids = $_POST ['id'];
		if (empty ( $ids )) {
			echo 0;
			exit ();
		}
		
		$list = $node->where ( "FIND_IN_SET(id, getChildLst($ids))" )->order ( 'id' )->select ();
		
		$arr = array ();
		foreach ( $list as $key => $value ) {
			$arr [] = $value ['id'];
		}
		$map ['id'] = array (
				'in',
				$arr 
		);
		$data ['node_id'] = array (
				'in',
				$arr 
		);
		
		$log ['uid'] = $this->mid;
		$log ['type'] = 2;
		$datas [] = L ( 'user' ) . ' - ' . L ( 'nodeManage' );
		if ($_POST ['__hash__'])
			unset ( $_POST ['__hash__'] );
		$datas [] = $_POST;
		$log ['data'] = serialize ( $datas );
		$log ['ctime'] = time ();
		M ( 'AdminLog' )->add ( $log );
		
		if ($node->where ( $map )->delete ()) {
			echo false !== $assess->where ( $data )->delete () ? '1' : '0';
		}
	}
	
	/**
	 * 获取节点信息
	 * Create Data <2013-05-02>
	 */
	public function getNodeInfo() {
		$node = model ( 'Node' );
		$id = intval($_GET['id']);
		if(!empty($id)) {
			$c = $node->where("id=$id")->find();
			if(false !== $c) {
				echo json_encode ( $c );
			} else {
				echo 0;
			}
		}
	}
	
	/**
	 * 编辑节点
	 * Create Data <2013-05-02>
	 */
	public function editorNode() {
		$node = model ( 'Node' );
		$id = $_POST ['id'];
		
		if (! empty ( $id )) {
			$data ['name'] = $_POST ['name'];
			$data ['title'] = $_POST ['title'];
			$data ['status'] = $_POST ['status'];
			
			$log ['uid'] = $this->mid;
			$log ['type'] = 3;
			$datas [] = L ( 'user' ) . ' - ' . L ( 'nodeManage' );
			if ($_POST ['__hash__'])
				unset ( $_POST ['__hash__'] );
			$datas [] = $_POST;
			$log ['data'] = serialize ( $datas );
			$log ['ctime'] = time ();
			M ( 'AdminLog' )->add ( $log );
			
			if (false !== $node->where ( "id=$id" )->save ( $data )) {
				$this->success ( L ( 'editor' ) . L ( 'success' ) );
			} else {
				$this->error ( L ( 'editor' ) . L ( 'fails' ) );
			}
		}
	}
	
	/**
	 * 转移用户组操作
	 * Create Data <2013-05-02>
	 */
	public function shiftUserGroup() {
		$ids = $_GET ['shiftIds'];
		
		$ids = explode ( ',', $ids );
		foreach ( $ids as $k => $v )
			if (! is_numeric ( $v ) || intval ( $v ) <= 0)
				unset ( $ids [$k] );
		$count = count ( $ids );
		$ids = implode ( ',', $ids );
		
		$lr = M ( 'Role' );
		$list = $lr->select ();
		
		$this->assign ( "list", $list );
		$this->assign ( "count", $count );
		$this->assign ( "ids", $ids );
		
		$this->display ();
	}
	
	/**
	 * 转移用户组
	 * Create Data <2013-05-02>
	 */
	public function shiftUserGroups() {
		$_POST ['gid'] = explode ( ',', $_POST ['gid'] );
		$_POST ['uid'] = explode ( ',', $_POST ['uid'] );
		if (empty ( $_POST ['gid'] ) || empty ( $_POST ['uid'] )) {
			echo 0;
			return;
		}
		$gid = $_POST ['gid'];
		$uid = $_POST ['uid'];
		
		$gid = is_array ( $gid ) ? $gid : explode ( ',', $gid );
		$uid = is_array ( $uid ) ? $uid : explode ( ',', $uid );
		
		/* 删除之前的配置 */
		$map ['user_id'] = array (
				'in',
				$uid 
		);
		$ru = M ( 'RoleUser' );
		$ru->where ( $map )->delete ();
		unset ( $map );
		
		/* 添加数据 */
		$sql = "INSERT INTO `" . C ( 'DB_PREFIX' ) . "role_user` (`role_id`,`user_id`) VALUES ";
		foreach ( $gid as $ggid ) {
			foreach ( $uid as $uuid ) {
				$sql .= "('{$ggid}', '{$uuid}'),";
			}
		}
		$sql = rtrim ( $sql, ',' );
		echo $ru->execute ( $sql ) > 0 ? 1 : 0;
	}
	
	/**
	 * 分配
	 * Create Data <2013-05-02>
	 */
	public function allocation() {
		$id = $_GET ['id'];
		if (! empty ( $id )) {
			$this->assign ( 'id', $id );
		}
		$this->display ();
	}
	
	/**
	 * 节点管理->树形结构
	 * Create Data <2013-05-02>
	 */
	public function nodeManage2() {
		$this->display();
	}
	
	/**
	 * 获取树节点，并以json格式返回 
	 * Create Data <2013-05-02>
	 */
	public function getJsonNode() {
		$node = model ( 'Node' );
		$access = M ( 'Access' );
		$roleId = $_POST ['id'];
		$arr = array ();
		$list = $node->order ( 'id' )->select ();
		foreach ( $list as $key => $value ) {
			$id = $value ['id'];
			$data ['role_id'] = $roleId;
			$data ['node_id'] = $id;
			if ($access->where ( $data )->select ()) {
				$arr [] = array (
						'id' => $id,
						'pId' => $value ['pid'],
						'name' => $value ['title'],
						'open' => true,
						'checked' => true 
				);
			} else {
				$arr [] = array (
						'id' => $id,
						'pId' => $value ['pid'],
						'name' => $value ['title'],
						'open' => false 
				);
			}
		}
		echo json_encode ( $arr );
	}
	
	/**
	 * 权限分配节点数据
	 * Create Data <2014-03-17>
	 */
	public function getJsonNodeTree(){
		$node = model ( 'Node' );
		$access = M ( 'Access' );
		$roleId = $_GET ['id'];
		$data ['role_id'] = $roleId;
		$arr = array ();
		$list = $node->order ( 'id' )->select ();
		$checkedList = $access->where ( $data )->field ('node_id') -> select();
		foreach ($checkedList as $key => $value){
			$checkedList[$key] = $checkedList[$key]['node_id'];
		}
		
		$arr = nodetree($list,$checkedList);
		echo json_encode ( $arr );
	}
	
	/**
	 * 权限分配
	 * Create Data <2013-05-02>
	 */
	public function rightsAllocation() {
		$nodeId = $_POST ['nodeId'];
		$roleId = $_POST ['roleId'];
		$node = model ( 'Node' );
		$access = M ( 'Access' );
		
		$access->where ( "role_id=$roleId" )->delete ();
		if (is_array ( $nodeId )) {
			$sql = "INSERT INTO `" . C ( 'DB_PREFIX' ) . "access` (`role_id`,`node_id`,`level`,`pid`) VALUES ";
			foreach ( $nodeId as $nid ) {
				$res = $node->where ( "id=$nid" )->find ();
				$sql .= "('{$roleId}', '{$nid}', '{$res['level']}', '{$res['pid']}'),";
			}
			$sql = rtrim ( $sql, ',' );
			echo $access->execute ( $sql ) > 0 ? 1 : 0;
		} else {
			echo 0;
		}
	}
	
	/**
	 * 推送配置
	 */
	public function pushConfig(){
		$pushConfig = include SITE_PATH . '/apps/admin/Conf/pushConfig.php';
		$this->assign("push",$pushConfig);
		$this->display();
	}
	
	/**
	 * 推送配置
	 */
	public function dopushConfig(){
		try {
			$filename = SITE_PATH . '/apps/admin/Conf/pushConfig.php';
			file_exists($filename) or touch($filename);
			if($_POST['__hash__']) unset($_POST['__hash__']);
			if($_POST['configname']) unset($_POST['configname']);
			$return = var_export($_POST, TRUE);
			if ($return) {
				file_put_contents($filename, "<?php \r\n return " . $return . ";");
			}
			$this->success('配置成功');
		} catch (Exception $e) {
			$this->error("请检查文件{$filename}是否有读写权限");
		}
	}
	
	/**
	 * 系统级推送
	 */
	public function syspush(){
		$role = M ( 'Role' );
		$list = $role->order ( 'id' )->select ();
		$this->assign ( 'list', $list );
		$this->display();
	}

	/**
	 * 应用级推送
	 */
	public function apppush(){
		$role = M ( 'Role' );
		$list = $role->order ( 'id' )->select ();
		$this->assign ( 'list', $list );
		$this->display();
	}
	
	/**
	 * 开始系统级推送
	 */
	public function dosyspush(){
		$res = $this->getUserId();
		$data['appid'] = uniqid();
		if(is_array($res)){
			$data['to'] = urlencode(implode('|',$res));
		}else{
			$data['pushid'] = $res;
		}
		$data['count'] = 0;
		$data['stamp'] = time("yyyyMMddHHmmss");
		$data['sign'] = md5(implode('',$data));
		echo json_encode($data);
	}
	
	/**
	 * 开始应用级推送
	 */
	public function doapppush(){
		$res = $this->getUserId();
		$data['appid'] = uniqid();
		if(is_array($res)){
			$data['to'] = urlencode(implode('|',$res));
		}else{
			$data['pushid'] = $res;
		}
		$data['count'] = 0;
		$data['stamp'] = time("yyyyMMddHHmmss");
		$data['sign'] = md5(implode('',$data));
		echo json_encode($data);
	}
	
	/**
	 * 获取推送用户id
	 * 
	 * 推送用户数量小于50，返回用户id数组 
	 * 
	 * 推送用户数量大于50，返回唯一pushid，并往mongodb push表更新数据
	 */
	private function getUserId(){
		$id = intval ( $_POST ['id'] );
		$type = intval ( $_POST ['type'] );
		$ru = M ( 'RoleUser' );
		$user = M ( 'User' );
		
		// 如果id=0，表示所有用户,获取所有用户的uid
		if ($id == 0) {
			$data ['is_active'] = array (
					'eq',
					'1'
			);
			$list = $user->where ( $data )->field ( 'uid' )->order ( 'uid' )->select ();
			$count = $user->where($data)->field('uid')->order('uid')->count();
		} else {
			$count = $ru->where ( "role_id=$id" )->count ();
			$list = $ru->where ( "role_id=$id" )->field('user_id as uid')->select ();
		}
		foreach ($list as $k => $v){
			$list[$k] = $v['uid'];
		}
		if($count < 4){
			return $list;
		}
		$pushid = uniqid();
		include_once( "./apps/weibo/Lib/Action/PushAction.class.php" );
		$pusha = new PushAction();
		$pusha -> add(array("userid" => $list,"pushid" => $pushid));
		return $pushid;
	}
	
}

?>